﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Samples.ServiceHosting.StorageClient;
using System.Data.Services.Client;

namespace Dtyo_WebRole
{
    public class DtyoDataSource
    {
        private DtyoDataContext _context;

        public DtyoDataSource()
        {
            StorageAccountInfo info = StorageAccountInfo.GetDefaultTableStorageAccountFromConfiguration();
            TableStorage.CreateTablesFromModel(typeof(DtyoDataContext), info);
            _context = new DtyoDataContext(info);
            _context.RetryPolicy = RetryPolicies.RetryN(3, TimeSpan.FromSeconds(1));
        }

        public IEnumerable<Department> SelectDepartmentList()
        {
            var results = from g in _context.Department
                          where g.PartitionKey == DateTime.UtcNow.ToString("MMddyyyy")
                          select g;
            return results.ToArray<Department>();
        }

        public Department SelectDepartment(String rowKey)
        {
            var result = from g in _context.Department
                         where g.RowKey == rowKey
                         select g;

            return result.First<Department>();
        }

        public Employee SelectEmployee(String rowKey)
        {
            var result = from g in _context.Employee
                         where g.RowKey == rowKey
                         select g;

            return result.First<Employee>();
        }

        public IEnumerable<Employee> SelectEmployeeList()
        {
            var results = from g in _context.Employee
                          where g.PartitionKey == DateTime.UtcNow.ToString("MMddyyyy")
                          select g;
            return results.ToArray<Employee>();
        }

        public void AddDepartment(Department newItem)
        {
            _context.AddObject("Department", newItem);
            _context.SaveChanges();
        }

        public void SaveDepartment(Department oldItem)
        {
            _context.UpdateObject(oldItem);
            _context.SaveChanges();
        }

        public void AddEmployee(Employee newItem)
        {
            _context.AddObject("Employee", newItem);
            _context.SaveChanges();
        }

        public void SaveEmployee(Employee oldItem)
        {
            _context.UpdateObject(oldItem);
            _context.SaveChanges();
        }


    }
}
